import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:shop/config/config.dart';
import 'package:shop/http/HttpUtil.dart';
import 'package:shop/route/my_route.dart';
import 'package:shop/shop/life/PayMima.dart';

import '../RefundType.dart';
class OrderDetail extends StatefulWidget {
  final String orid;//订单ID
  final String orStatus;//订单状态
  OrderDetail({Key key, this.orid, this.orStatus}) : super(key: key);

  @override
  _OrderDetail createState() => _OrderDetail(orid,orStatus);
}

class _OrderDetail extends State<OrderDetail> {
  String orId;            //订单ID
  String orstatus;        //订单状态
  List orderDetailList=[];//订单详情集合
  var order={};           //订单
  int peisong = 1;        //订单配送类型

  _OrderDetail(this.orId, this.orstatus){
    this.orId=orId;
    this.orstatus=orstatus;
    _onLoading();
  }

  // @override
  // void initState() {
  //   super.initState();
  //   _onLoading();
  // }

  void _onLoading() async{
    // var x = await HttpUtil().get("/app/order/getOrderById?orId=${orId}");
    var x = await HttpUtil().get("/waimai/mOder/getMOrderById?orId=${orId}");
    if(x['code']==200){
      order=x['data'];
      peisong = x['data']['orPeisongtype'];
      // print("配送类型："+peisong.toString()+" 订单状态："+orstatus);
      orderDetailList=x['data']['morderDetailList'];
    }
    if(mounted){
      setState(() {

      });
    }
  }

// 显示订单中的商品
  Container _showGoods(item){
    // print(item['num']);
    return Container(
      height: 80,
      child:Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Checkbox(value: item['isSelect'], onChanged: (val){// 点击勾选
            item['isSelect']=val;
            setState(() {

            });
          }),
          Image.asset("assets/phone2.jpg",width: 200,),
          Expanded(
            child: Column(
              children: [
                Text(item['gname']),
                Text("红色;8+256GB"),
                Text("￥${item['gprice']}"),
                Container(
                  child: Row(
                    children: [
                      GestureDetector(onTap: (){
                        if(item['num']>1)
                          item['num']--;
                        setState(() {

                        });
                      },
                        child:Container(
                          width: 30,
                          height: 20,
                          decoration: BoxDecoration(
                              border: Border.all(
                                color: Colors.black12,
                                width: 1.0,
                              ),
                              borderRadius: BorderRadius.circular(3.0)
                          ),
                          child:Center(child: Text("-"),) ,
                        )
                      ),
                      Text("${item['num']}"),
                      GestureDetector(onTap: (){
                        item['num']++;
                        setState(() {

                        });
                      },
                      child:Container(
                        width: 30,
                        height: 20,
                        decoration: BoxDecoration(
                          border: Border.all(
                            color: Colors.black12,
                            width: 1.0,
                          ),
                          borderRadius: BorderRadius.circular(3.0)
                        ),
                        child:Center(child:  Text("+"),),
                      )),
                    ],
                  ),
                )// Positioned(child: Text("*1"),right: 10,),
              ],
            )
          )
        ],
      ) ,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("订单详情"),
        centerTitle: true,
      ),
      body: Column(
        children: <Widget>[
          new Expanded(
            child: Container(
              padding:EdgeInsets.all(10),
              child: ListView(
                children: [
                  Container(
                    decoration: BoxDecoration(color: Colors.white,borderRadius: BorderRadius.circular(10)),
                    padding: EdgeInsets.all(10),
                    child: Row(
                      children: [
                        Row(
                          children: [
                            Icon(Icons.add_location),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children:[
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  children: [
                                    Text(_getHeadTitle(orstatus),style: TextStyle(fontSize: 18),),
                                  ],),
                                Text("感谢您对我们的支持",style: TextStyle(color: Colors.black12))
                              ]),
                          ],),
                        // Icon(Icons.navigate_next),
                      ],
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,)
                  ),
                  Container(
                    decoration: BoxDecoration(color: Colors.white,borderRadius: BorderRadius.circular(10)),
                    padding: EdgeInsets.all(10),
                    margin: EdgeInsets.only(top: 10),
                    child: Column(
                      children: [
                        Row(children: [
                          Icon(Icons.card_giftcard),
                          Text(order['merchant']==null ? "" : order['merchant']['mname']),
                        ]),
                        _getGoods(orderDetailList,orstatus),
                        // Row(
                        //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        //   children: [
                        //     Expanded(child: Text("订单备注:送礼品2安全提示公司人人参果是多少身体也是搜索三个")) ,
                        //   ],),
                      ],
                    ),
                  ),
                  getOrderMessage(order),
                ],
              ),
              color: Colors.black12,
            )
          ),
          Row(
            children: <Widget>[
              Expanded(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: _getPayStatus(orstatus, order)
                ),
              )
            ],
          )
        ]
      ),
    );
  }

  List<Widget> _getPayStatus(orStatus,orders){
    return [
      Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,children: [
        Text("实付：￥"+orders['orPrice'].toString(),style: TextStyle(color: Colors.red, fontSize: 18)),
        SizedBox(width: 20,),
        Text("共"+orders['orTotalnum'].toString()+"件")
      ]
      ),
      orStatus=='0' ?
      GestureDetector(child:  Container(
        alignment: Alignment.center,
        child: new Text("立即付款", style: TextStyle(color: Colors.white)),
        width: 130,
        height: 50,
        color:Colors.red,
      ),
          onTap: () async {
            SharedPreferences prefs = await SharedPreferences.getInstance();
            String userId = prefs.getString("userId");
            MyRoute.push(PayMima(money: orders['orPrice'],unionid: orders['unionid'],userId: userId,type: 4));
          }
      )
          :
      // GestureDetector(child:  Container(
      //   alignment: Alignment.center,
      //   child: new Text("已付款" ,style: TextStyle(color: Colors.white)),
      //   width: 130,
      //   height: 50,
      //   color:Colors.grey,
      // )
      // )
    Row(
      children: [
        orStatus=='1' ?
        GestureDetector(child:  Container(
          alignment: Alignment.center,
          child: new Text("商家已接单", style: TextStyle(color: Colors.white)),
          // child: new Text("申请退款", style: TextStyle(color: Colors.white)),
          width: 130,
          height: 50,
          color:Colors.red,
        ),onTap: () async {
          var value = await MyRoute.push(RefundType(odid: orders['orderDetailList'][0]['odId'].toString(),orid: orders['orderDetailList'][0]['orId'].toString(),gid: orders['orderDetailList'][0]['gid'].toString(),orStatus: orStatus,));
          if(value==1){
            MyRoute.pop(1);
          }
          },
        ) :
        GestureDetector(child:  Container(
        alignment: Alignment.center,
          child: new Text(orStatus=='2' ? "商家出餐完成" : (orStatus=='3' ? "骑手已取货，配送中" : (orStatus=='4' ? "已送达，待评价" : (orStatus=='5' ? "已评价" : (orStatus=='6' ? "退货换货申请中" : (orStatus=='7' ? "退货换货完成" : (orStatus=='8' ? "退款完成" : "取消订单")))))) ,style: TextStyle(color: Colors.white)),
          width: 130,
          height: 50,
          color:Colors.grey,
          ))
      ],
    )];
  }

  Widget _getGoods(OrderDetailList,orStatus){
    List<Widget> x = [];
    for(int i=0;i<OrderDetailList.length;i++){
      x.add( Container(child: Row(children: [
        // Image.network("https://www.itying.com/images/flutter/list2.jpg",fit: BoxFit.cover,width: 80,height: 80,),
        CachedNetworkImage(imageUrl: Config.getInstance().getHost()+OrderDetailList[i]['mgoods']['gimages'],width: 60,height: 60,),
        Expanded(child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(children: [ Padding(padding: EdgeInsets.only(left: 10,top: 15 ),child: Container(width:ScreenUtil().setWidth(330),child: Expanded(child: Text(OrderDetailList[i]['mgoods']['gname'],maxLines: 1,),),))]),
            Row(children: [ Padding(padding: EdgeInsets.only(left: 10,top: 0 ),child:OrderDetailList[i]['guiges']==null ? Text("") : Text(OrderDetailList[i]['guiges']),)]),
            Row(children: [
              Padding(padding: EdgeInsets.only(left: 10),child: Text("￥"+OrderDetailList[i]['odCost'].toString())),
              Padding(padding: EdgeInsets.only(left: 10),child: Text("数量:"+OrderDetailList[i]['odNum'].toString())),
              Align(
                alignment: Alignment.centerRight,
                child: Container(
                  padding: EdgeInsets.fromLTRB(6, 3, 6, 3),
                  child:
                  GestureDetector(child:  Container(
                    alignment: Alignment.center,
                    // child:peisong==0 ? Text('') : orStatus!='2' && orStatus!='4'? null : Text("申请售后"),
                    decoration: BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(5)) ,
                      border: Border.all(color: Colors.black12 , width: 1) ,
                    ),
                  ),
                    onTap: () async {
                      var x = await HttpUtil().get("app/refunds/judgeRefundExit?odid="+OrderDetailList[i]['odId']);
                      if(x['code']==200){
                        MyRoute.push(RefundType(odid: OrderDetailList[i]['odId'],orid: OrderDetailList[i]['orId'],gid: OrderDetailList[i]['goods']['gid'],orStatus: orStatus,));
                      }else{
                        Fluttertoast.showToast(
                          msg: x['msg'],
                          toastLength: Toast.LENGTH_SHORT,
                          gravity: ToastGravity.BOTTOM,
                          timeInSecForIosWeb: 2,
                          backgroundColor: Colors.black45,
                          textColor: Colors.white,
                          fontSize: 16.0
                        );
                      }
                    },
                  ),
                )
              )
            ],
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
            )
          ],
        )
        )
      ],
      ),
        height: 90,
      ) );
    }
    return Container(
      child: Column(children: x),
    ) ;
  }

  String _getHeadTitle(status){
    String s='';
    switch(status){
      case '0':s="待支付";break;
      case '1':s="商家已接单";break;
      case '2':s="商家出餐完成";break;
      case '3':s="骑手已取货，配送中";break;
      case '4':s="已送达，待评价";break;
      case '5':s="已评价";break;
      case '6':s="退换货申请中";break;
      case '7':s="退换货完成";break;
      case '8':s="退款完成";break;
      case '9':s="取消订单";break;
      // case '1':s="正在发货";break;
      // case '2':s="努力配送中";break;
      // case '3':s="交易成功";break;
      // case '4':s="售后申请中";break;
      // case '5':s="售后完成";break;
      // case '6':s="退款完成";break;
    }
    return s;
  }

  Widget getOrderMessage(orders){
    return Container(
      decoration: BoxDecoration(color: Colors.white,borderRadius: BorderRadius.circular(10)),
      padding: EdgeInsets.all(10),
      margin: EdgeInsets.only(top: 10),
      child: Column(children: [
        Row(children: [Text("订单信息",style: TextStyle(fontWeight: FontWeight.bold),)],) ,
        Padding(padding: EdgeInsets.only(top: 10),child:
          Row(children: [
            Text(orders['address']!=null ? "收货信息：" : "自提信息："),//"流行守望者，18907331215，湖南省株洲市天元区嵩山路街道珠江北路幸福大厦909"
            // Expanded(child: Text(orders['address']!=null ? orders['zitidian']==null ? ("联系人："+orders['address']['adName']+"  联系方式："+orders['address']['adPhone']+"  收货地址："+orders['address']['addressDetail']) : ("自提点名称："+orders['zitidian']['zitiName']+"  联系方式："+orders['zitidian']['phone']+"  自提地址："+orders['zitidian']['zitiDetail']) : ""))
            Expanded(child: Column(
                children: [
                  // Text(orders['address']!=null ? ( orders['zitidian']!=null ? "自提点名称："+orders['zitidian']['zitiName'] : "联系人："+orders['address']['adName'] ): ""),
                  // Text(orders['address']!=null ? ( orders['zitidian']!=null ? "联系方式："+orders['zitidian']['phone'] : "联系方式："+orders['address']['adPhone'] ) : ""),
                  // Text(orders['zitidian']!=null ? "自提点名称："+orders['zitidian']['zitiName'] : "联系人："+orders['address']['adName']),
                  // Text(orders['zitidian']!=null ? "联系方式："+orders['zitidian']['phone'] : "联系方式："+orders['address']['adPhone']),
                  Text("联系人："+orders['address']['adName']),
                  Text("联系方式："+orders['address']['adPhone']),
                  Row(children: [
                    // Expanded(child: Text(orders['address']!=null ? ( orders['zitidian']!=null ? "自提地址："+orders['zitidian']['zitiDetail'] : "收货地址："+orders['address']['addressDetail'] ): ""))
                    Expanded(child: Text(orders['zitidian']!=null ? "自提地址："+orders['zitidian']['zitiDetail'] : "收货地址："+orders['address']['addressDetail']))
                  ],)
                ], crossAxisAlignment: CrossAxisAlignment.start
            ))
          ])
        ),
        Padding(padding: EdgeInsets.only(top: 10),child: Row(children: [
          Text("订单编号："),
          Expanded(child: Text(orders['orOrdernumber']!=null?orders['orOrdernumber']:"")),
          GestureDetector(child: Text("复制"),onTap: (){
            ClipboardData data = new ClipboardData(text:orders['orOrdernumber']!=null?orders['orOrdernumber']:"");
            Clipboard.setData(data);
            Fluttertoast.showToast(
                msg: "复制成功",
                toastLength: Toast.LENGTH_SHORT,
                gravity: ToastGravity.BOTTOM,
                timeInSecForIosWeb: 2,
                backgroundColor: Colors.black45,
                textColor: Colors.white,
                fontSize: 16.0
            );
          },)
        ])),
        Padding(padding: EdgeInsets.only(top: 10),child: Row(children: [
          Text("订单备注："),
          Expanded(child: Text(orders['orRemark']!=null&&orders['orRemark']!='null'?orders['orRemark']:""))
        ])
        ),
        Padding(padding: EdgeInsets.only(top: 10),child: Row(children: [
          Text("下单时间："),
          Expanded(child: Text(orders['orTime']!=null?orders['orTime']:"")),
        ])
        ),
        Padding(padding: EdgeInsets.only(top: 10),child: Row(children: [
          Text("付款时间："),
          Expanded(child: Text(orders['orPayTime']!=null ? orders['orPayTime'] : "还未付款~")),
        ])
        ),
        Padding(padding: EdgeInsets.only(top: 10),child: peisong==1 ? Row(children: [
          Text("发货时间："),
          Expanded(child: Text(orders['orFahuoTime']!=null ? orders['orFahuoTime'] : "还未发货~")),
        ]) : Row(),
        ),
        Padding(padding: EdgeInsets.only(top: 10),child:Row(children: [
          Text("收货时间："),
          Expanded(child: Text(orders['orFinishtTime']!=null ? orders['orFinishtTime'] : "还未收货~")),
        ])
        ),
      ],),
    );
  }

}